// uCapture.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include "uCapture.h"


#ifdef _MANAGED
#pragma managed(push, off)
#endif

HMODULE g_module;

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		g_module = hModule;
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
    return TRUE;
}

#ifdef _MANAGED
#pragma managed(pop)
#endif

UCAPTURE_API HBITMAP CreateBitmap2(IDispatch *pApp, int x, int y)
{
	HBITMAP hBitmap = 0;
	IViewObject2*	pViewObject = NULL;
	HRESULT hRes =  pApp->QueryInterface(IID_IViewObject2, (void**)&pViewObject);
	if (SUCCEEDED(hRes))
	{
		// Create memory DC
		HDC hdcMem = CreateCompatibleDC(GetDC(NULL));
		// Create bitmap
		hBitmap = CreateCompatibleBitmap (GetDC(NULL), x, y);
		// Select bitmap into DC
		HBITMAP hOldBitmap = (HBITMAP)SelectObject(hdcMem, hBitmap);

		RECTL rcBounds = { 0, 0, x, y };
		hRes = pViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL, GetDC(NULL), hdcMem, &rcBounds, NULL, NULL, 0);
		if (SUCCEEDED(hRes))
		{
			// Buil the DIB
			int imgsize = ((((x * 24)+31) & ~31) >> 3)*y;
			int size = imgsize+sizeof (BITMAPINFOHEADER);
			if (char *dib = new char[size])
			{

				BITMAPINFO	*pbmi = (BITMAPINFO *)dib;
				BITMAPINFOHEADER *lpBIH = &pbmi->bmiHeader;

				lpBIH->biSize			= sizeof (BITMAPINFOHEADER);
				lpBIH->biWidth			= x;
				lpBIH->biHeight			= y;
				lpBIH->biPlanes			= 1;
				lpBIH->biBitCount		= 24;
				lpBIH->biCompression	= BI_RGB;
				lpBIH->biSizeImage		= imgsize;
				lpBIH->biXPelsPerMeter  = 0;
				lpBIH->biYPelsPerMeter  = 0;
				lpBIH->biClrUsed        = 0;
				lpBIH->biClrImportant   = 0;

				SelectObject (hdcMem, hOldBitmap);
				hOldBitmap=NULL;

				int i = GetDIBits (hdcMem, hBitmap,	0, y, dib+sizeof(BITMAPINFOHEADER), pbmi, DIB_RGB_COLORS);
				delete[] dib;
			}
		}
		
		if (hOldBitmap)
			SelectObject (hdcMem, hOldBitmap);

		DeleteDC(hdcMem);

		pViewObject->Release();
		
	}
	return hBitmap;
}
